import React, { Component } from "react";
import Scrollbars from "react-custom-scrollbars";
import { Modal, Input, message, Icon, Button, Upload } from "antd";
import { stampToDate, fixedZero } from "../../utils/index.js";
import { WS_PREFIX, IMAGES_URL, IM_PREFIX } from "../../utils/constants";
import ReconnectingWebSocket from "../../utils/ReconnectingWebSocket";
import AppealModal from "./AppealModal";
import CancelPopup from "./CancelPopup";
import ReceiptPopup from "./ReceiptPopup";
import "./modal.css";

const chatPassword = "123456";

class PayModal extends Component {
  constructor(props) {
    super(props);
    this.state = {
      bankInfo: "",
      askUserName: "",
      popup: "",
      messageValue: "",
      messageList: [],
      remainingTime: "",
      order: props.order,
      getMessage: true
    };
  }
  request = window.request;

  componentDidMount() {
    const { order } = this.props;
    const { askUserId, userId, remarks, remainingTime, status } = order;

    this.setState({ remainingTime: remainingTime });

    // 打开订单 scoket
    this.openOrderSocket();
    this.openChatSocket();
    // 如果 有remainingTime 开启倒计时 处于下单状态
    if (remainingTime > 0 && status === 0) {
      this.clockTimeout(true);
    }
  }

  componentWillUnmount() {
    clearTimeout(this.timer);
    clearInterval(this.orderItemInterval);

    this.orderItemWS && this.orderItemWS.close();
    this.chatWS && this.chatWS.close();
  }

  clockTimeout = flag => {
    if (flag) {
      this.timer = setTimeout(() => {
        const { remainingTime, order } = this.state;
        const { status } = order;
        if (remainingTime > 0 && status === 0) {
          this.setState({ remainingTime: remainingTime - 1 });
          this.clockTimeout(true);
        } else {
          this.clockTimeout(false);
        }
      }, 1000);
    } else {
      clearTimeout(flag);
    }
  };

  //根据用户ID获取 卖方 用户支付信息
  getBankInfo = id => {
    this.request(`/offline/bankInfo/${id}`, {
      method: "GET"
    }).then(json => {
      if (json.code === 10000000) {
        this.setState({ bankInfo: json.data });
      } else {
        message.error(json.msg);
      }
    });
  };
  // 获取对方名字
  getBankInfoName = id => {
    this.request(`/offline/bankInfo/${id}`, {
      method: "GET"
    }).then(json => {
      if (json.code === 10000000 && json.data) {
        this.setState({
          askUserName: json.data.realName ? json.data.realName : ""
        });
      } else {
        message.error(json.msg);
      }
    });
  };

  //打开订单 socket
  openOrderSocket = () => {
    let { order } = this.state;
    const { userId } = order;
    this.orderItemWS = new ReconnectingWebSocket(
      `${WS_PREFIX}/c2cUser?${userId}`
    );

    this.orderItemWS.onopen = () => {
      if (this.orderItemWS.readyState === 1) {
        this.orderItemWS.send("ping");
      }
    };

    this.orderItemInterval = setInterval(() => {
      if (this.orderItemWS.readyState === 1) {
        this.orderItemWS.send("ping");
      }
    }, 1000 * 10);

    this.orderItemWS.onmessage = evt => {
      if (evt.data === "pong") {
        return;
      }
      const record = JSON.parse(evt.data);
      // console.log(order, record);
      if (record.subOrderId) {
        if (order.subOrderId === record.subOrderId) {
          order.status = record.status;
          // console.log(order.status, record.status);
          this.setState({ order });
        }
      }
    };
  };
  // 打开 聊天socket
  openChatSocket = () => {
    const { order } = this.state;
    const { subOrderId, userId, askUserId } = order;
    this.chatWS = new ReconnectingWebSocket(
      `${IM_PREFIX}?username=${subOrderId}_${userId}&password=${chatPassword}`
      /*  `ws://192.168.1.82/bbex/im?username=${subOrderId}_${userId}&password=${chatPassword}` */
    );

    this.chatWS.onopen = () => {
      const msgKey = subOrderId + "_" + userId;
      const offlineMsg = '{"cmd":19,"type":"0","userId":"' + msgKey + '"}';
      if (this.chatWS.readyState === 1) {
        this.chatWS.send(offlineMsg);
      }
    };

    this.chatWS.onmessage = evt => {
      if (evt.data === "pong") {
        return;
      }
      const json = JSON.parse(evt.data);
      const { askUserId, subOrderId } = order;
      // console.log("message", json);
      if (json.command === 20 && json.code === 10016) {
        //离线消息
        const friends = json.data.friends;
        // console.log("friends", friends);
        const msgKey = subOrderId + "_" + askUserId;
        if (
          friends &&
          Object.keys(friends).some(item => {
            return item === msgKey;
          })
        ) {
          let messageList = friends[msgKey].map(item => {
            item.userType = 0; //0是对方的消息
            return item;
          });
          // console.log("messageList", messageList);
          this.setState({ messageList });
        }
      } else if (json.command === 11) {
        // 收到对方的消息
        let { messageList } = this.state;
        let newMsg = json.data;

        newMsg.userType = 0; // 0是对方的消息
        if (Array.isArray(messageList)) {
          messageList.push(newMsg);
          // console.log("messageList", messageList);
          this.setState({ messageList });
        }
      } else if (json.command === 20 && json.code === 10018) {
        // console.log("jsonhistory", json);
        if (json.data && json.data.friends) {
          const friends = json.data.friends;
          const msgKey = subOrderId + "_" + askUserId;
          if (
            friends &&
            Object.keys(friends).some(item => {
              return item === msgKey;
            })
          ) {
            let { messageList } = this.state;
            let myList = friends[msgKey].map(item => {
              let id = item.from.split("_")[1];
              if (id === askUserId) {
                item.userType = 0; //0是对方的消息
              } else {
                item.userType = 1;
              }
              return item;
            });

            messageList = myList;

            this.setState({ messageList });

            const { chatScroll } = this.refs;
            chatScroll && chatScroll.scrollToBottom();
          }
        }
      }
    };
  };

  //获取历史消息
  getHistoryMsg = () => {
    if (this.chatWS) {
      const { order } = this.state;
      const { subOrderId, userId, askUserId } = order;
      const msgKey = subOrderId + "_" + userId;
      const friendId = subOrderId + "_" + askUserId;
      const historyMsg =
        '{"cmd":19,"type":"1","fromUserId":"' +
        friendId +
        '","userId":"' +
        msgKey +
        '"}';
      if (this.chatWS.readyState === 1) {
        this.chatWS.send(historyMsg);
        this.setState({ getMessage: false });
      }
    }
  };

  // 发送消息
  sendMessage = () => {
    let { messageValue, order, messageList } = this.state;
    if (messageValue) {
      const { askUserId, userId, subOrderId } = order;
      if (this.chatWS) {
        const createTime = new Date().getTime();
        const msg =
          '{"from": "' +
          subOrderId +
          "_" +
          userId +
          '","to": "' +
          subOrderId +
          "_" +
          askUserId +
          '","cmd":11,"createTime":' +
          createTime +
          ',"chatType":"2","msgType": "0","content": "' +
          messageValue +
          '"}';
        if (this.chatWS.readyState === 1) {
          this.chatWS.send(msg);
        }

        let myMsg = {
          from: userId,
          to: askUserId,
          content: messageValue,
          userType: 1,
          msgType: 0,
          createTime
        };

        if (Array.isArray(messageList)) {
          messageList.push(myMsg);
          const { chatScroll } = this.refs;
          chatScroll && chatScroll.scrollToBottom();
        }

        this.setState({ messageValue: "", messageList });
      }
    }
  };

  // 确认付款
  handlePay = () => {
    let { order } = this.props;

    const { totalPrice, radomNum } = order;
    const receiptProps = {
      totalPrice,
      radomNum,
      type: "pay"
    };
    this.setState({
      popup: (
        <ReceiptPopup
          {...receiptProps}
          onCancel={() => {
            this.setState({ popup: false });
          }}
          onOk={() => {
            this.request("/offline/buy/confirm", {
              body: {
                orderId: order.orderId,
                subOrderId: order.subOrderId
              }
            }).then(json => {
              if (json.code === 10000000) {
                message.success("确认付款成功");
                const status = json.data;
                order.status = status;
                this.setState({ order, popup: "" });
              } else {
                message.error(json.msg);
              }
            });
          }}
        />
      )
    });
  };

  //确认收款
  confirmReceive = () => {
    let { order } = this.state;
    const { totalPrice, radomNum } = order;
    const receiptProps = {
      totalPrice,
      radomNum,
      type: "receive"
    };
    this.setState({
      popup: (
        <ReceiptPopup
          {...receiptProps}
          onCancel={() => {
            this.setState({ popup: false });
          }}
          onOk={() => {
            this.request("/offline/sell/confirm", {
              body: {
                orderId: order.orderId,
                subOrderId: order.subOrderId
              }
            }).then(json => {
              if (json.code === 10000000) {
                message.success("确认收款成功！");
                const status = json.data;
                order.status = status;
                this.setState({ order, popup: "" });
              } else {
                message.error(json.msg);
              }
            });
          }}
        />
      )
    });
  };

  // 撤销交易
  cancelOrderSubmit = () => {
    let { order } = this.state;
    this.request("/offline/detail/cancel", {
      body: {
        orderId: order.orderId,
        subOrderId: order.subOrderId
      }
    }).then(json => {
      if (json.code === 10000000) {
        message.success("撤销交易成功");
        const status = json.data;
        order.status = status;
        this.setState({ order });
      } else {
        message.error(json.msg);
      }
    });
  };

  //撤销交易
  cancelOrder = () => {
    this.setState({
      popup: (
        <CancelPopup
          onCancel={() => {
            this.setState({ popup: "" });
          }}
          onOk={() => {
            this.setState({ popup: "" });
            this.cancelOrderSubmit();
          }}
        />
      )
    });
  };

  //检查申诉
  checkAppeal = (subOrderId, callback) => {
    this.request("/offline/appeal/check", {
      method: "GET",
      body: {
        subOrderId
      }
    }).then(json => {
      if (json.code === 10000000) {
        callback(true);
      } else {
        message.destroy();
        message.warn(json.msg, 1);
        callback(false);
      }
    });
  };

  messageChange = e => {
    this.setState({ messageValue: e.target.value });
  };

  // 提交申诉
  submitAppeal = result => {
    this.request("/offline/appeal/doappeal", {
      body: result
    }).then(json => {
      if (json.code === 10000000) {
        message.success("提交成功", 1);
        this.closeAppealModal();
      } else {
        message.destroy();
        message.warn(json.msg, 1);
      }
    });
  };

  closeAppealModal = () => {
    this.setState({ popup: "" });
  };

  //点击申请客服处理
  handleAppeal = () => {
    const { order } = this.state;
    const { subOrderId } = order;

    //检查是否可以申诉
    this.checkAppeal(subOrderId, check => {
      if (check) {
        this.setState({
          popup: (
            <AppealModal
              onCancel={() => {
                this.closeAppealModal();
              }}
              onOk={result => {
                let params = result;
                params.subOrderId = subOrderId;
                this.submitAppeal(params);
              }}
            />
          )
        });
      }
    });
  };

  //显示 图片 id
  showImagePopup = id => {
    this.setState({
      popup: (
        <Modal
          visible={true}
          className="c2c-code-popup"
          footer={null}
          onCancel={() => {
            this.setState({ popup: "" });
          }}
        >
          <img
            alt="二维码"
            style={{ width: "100%" }}
            src={`${IMAGES_URL}/${id}`}
          />
          {/*  <img alt="二维码" style={{ width: '100%' }} src={`${IMAGES_URL}/image/2018/9/19/239ae7bea97549c49a95981b9cc0140c.jpg?x-oss-process=style/uesstyle`}/> */}
        </Modal>
      )
    });
  };

  showChatImagePopup = imgUrl => {
    this.setState({
      popup: (
        <Modal
          visible={true}
          className="c2c-code-popup"
          footer={null}
          onCancel={() => {
            this.setState({ popup: "" });
          }}
        >
          <img alt="二维码" style={{ width: "100%" }} src={imgUrl} />
        </Modal>
      )
    });
  };

  render() {
    const { onCancel } = this.props;
    const {
      popup,
      messageValue,
      order,
      messageList,
      remainingTime,
      getMessage
    } = this.state;
    const {
      askUserMobile,
      subOrderId,
      remarks,
      status,
      price,
      symbol,
      totalPrice,
      volume,
      radomNum,
      sellBankBranchName,
      sellBankName,
      sellBankNo,
      alipayNo,
      wechatNo,
      alipayQrcodeId,
      wechatQrcodeId,
      askUserName,
      userName
    } = order;

    const sellerName = remarks === "buy" ? askUserName : userName;

    const props = {
      action: "https://images.uescoin.com/upload",
      showUploadList: false,
      beforeUpload: file => {
        const isImage = file.type.indexOf("image") > -1;
        if (!isImage) {
          message.error("请上传图片");
        }

        return isImage;
      },
      onChange(info) {
        if (info.file.status !== "uploading") {
          console.log(info.file, info.fileList);
        }
        if (info.file.status === "done") {
          console.log(`${info.file.response}`);
        }
      }
    };

    let myRemainingTime = "----";
    if (remainingTime > 0) {
      let hour = parseInt(remainingTime / 60);
      hour = fixedZero(hour);
      let minute = remainingTime % 60;
      minute = fixedZero(minute);
      myRemainingTime = `${hour}分${minute}秒`;
    }

    // console.log("messageList", messageList);
    return (
      <Modal
        title="支付"
        visible
        width={800}
        wrapClassName="v-center-modal"
        okText="确认"
        cancelText="取消"
        onCancel={onCancel}
        footer={null}
      >
        <ul className="c2c-pay-modal">
          <li className="c2c-order-detail">
            <h4>
              订单号 : <span style={{ marginLeft: 10 }}>{subOrderId}</span>
            </h4>
            <div className="c2c-total">
              数量 :{" "}
              <span style={{ marginLeft: 10 }}>
                {volume} {symbol}
              </span>
            </div>
            <div className="c2c-price">
              单价 :{" "}
              <span style={{ marginLeft: 10 }}>
                {price} CNY/
                {symbol}
              </span>
            </div>
            <div className="c2c-total">
              总价 : <span className="active" style={{fontSize: 22}}>{totalPrice} CNY</span>
            </div>
            <div>
              付款参考号 :{" "}
              <span className="active" style={{ marginLeft: 12 }}>
                {radomNum}
              </span>
            </div>

            <div className="c2c-pay-style">
              <p className="style-title">卖方收款方式</p>
              <ul>
                {sellBankNo && (
                  <li>
                    <i
                      className="iconfont icon-copy copy-btn"
                      data-clipboard-text={`${sellerName} ${sellBankNo} ${sellBankName}`}
                    />
                    <span className="style-title">银行卡</span>
                    <span>{sellerName}</span>
                    <span>{sellBankNo}</span>
                    <span>{sellBankName}</span>
                    <span>{sellBankBranchName}</span>
                  </li>
                )}
                {alipayQrcodeId && (
                  <li>
                    <i
                      className="iconfont icon-copy copy-btn"
                      data-clipboard-text={`${sellerName} ${alipayNo}`}
                    />
                    <span className="style-title">支付宝</span>
                    <span>{sellerName}</span>
                    <span>{alipayNo}</span>
                    <i
                      className="iconfont icon-erweima"
                      onClick={() => {
                        this.showImagePopup(alipayQrcodeId);
                      }}
                    />
                  </li>
                )}
                {wechatQrcodeId && (
                  <li>
                    <i
                      className="iconfont icon-copy copy-btn"
                      data-clipboard-text={`${sellerName} ${wechatNo}`}
                    />
                    <span className="style-title">微{"  "}信 </span>
                    <span>{sellerName}</span>
                    <span>{wechatNo}</span>
                    <i
                      className="iconfont icon-erweima"
                      onClick={() => {
                        this.showImagePopup(wechatQrcodeId);
                      }}
                    />
                  </li>
                )}
              </ul>
            </div>
            <div className="pay-message">
              {status === 0 &&
                (remarks === "buy" ? (
                  <div>
                    待支付，请于
                    <span className="pay-time">{myRemainingTime}</span>
                    内向 {askUserName} 支付
                    <span className="active">
                      {" "}
                      {totalPrice}
                      CNY{" "}
                    </span>
                  </div>
                ) : (
                  <div>
                    待收款, {askUserName} 将在
                    <span className="pay-time">{myRemainingTime}</span>
                    向您 支付
                    <span className="active">
                      {" "}
                      {totalPrice}
                      CNY{" "}
                    </span>
                  </div>
                ))}
              {status === 1 &&
                (remarks === "buy" ? (
                  <div>
                    您向 {askUserName} 支付了
                    <span className="active">
                      {" "}
                      {totalPrice}
                      CNY{" "}
                    </span>
                  </div>
                ) : (
                  <div>
                    {askUserName} 向您 支付了
                    <span className="active">
                      {" "}
                      {totalPrice}
                      CNY{" "}
                    </span>
                  </div>
                ))}
            </div>
            <div className="pay-btn">
              {remarks === "buy" && status === 0 && (
                <Button
                  type="primary"
                  onClick={() => {
                    this.handlePay();
                  }}
                >
                  {"我已付款给商家"}
                </Button>
              )}
              {remarks === "buy" && status === 1 && (
                <Button type="primary" size="large" disabled>
                  {"我已付款给商家"}
                </Button>
              )}
              {remarks === "sell" && status === 0 && (
                <Button size="large" disabled style={{ color: "#dadada" }}>
                  {"等待商家确认付款"}
                </Button>
              )}
              {remarks === "sell" && status === 1 && (
                <Button
                  type="primary"
                  onClick={() => {
                    this.confirmReceive();
                  }}
                >
                  {"确认收款"}
                </Button>
              )}

              {remarks !== "sell" && (status === 0 || status === 1) && (
                <div
                  className="cancel"
                  onClick={() => {
                    this.cancelOrder();
                  }}
                >
                  取消订单
                </div>
              )}
              {status === 2 && <div className="order-status">订单已完成</div>}
              {status === 4 && <div className="order-status">订单被申诉</div>}
              {status === 9 && <div className="order-status">订单已取消</div>}
            </div>
            <div className="notice-text">
              <p>转账注意事项 : </p>
              <p>
                1. 在转账过程中,请
                <span> 勿备注类似USDT,UES等信息 </span>
                ,防止造成您的转账被拦截,由此造成的损失由转账方负责
              </p>
              <p>
                2.
                <span> 请勿使用非平台实名的银行卡/支付宝等进行转款 </span>
                ,否则卖家可拒绝成交并投诉.
              </p>
              <p>
                3.
                若交易金额大于50,000CNY,法定假日或工作日17:00点以后汇款到银行卡可能造成到账不及时,请分批支付保证及时到账,若未及时到账,卖家有权拒绝成交.
              </p>
              <p>
                4.
                买家给卖家付款时，请使用平台显示的卖家收款信息，勿向卖家私自发的收款帐号转账，否则由此产生的争议，由买家自行承担。
              </p>
            </div>
          </li>
          <li className="c2c-chat-box">
            <header>
              <div>{askUserName && askUserName.charAt(0)}</div>
              <ul>
                <li>{askUserName}</li>
                <li>电话: {askUserMobile}</li>
              </ul>
              {status === 1 && (
                <h4 onClick={this.handleAppeal}>
                  <i className="iconfont icon-kefu" />
                  申请客服处理
                </h4>
              )}
            </header>
            <Scrollbars ref="chatScroll" style={{ height: 380, width: 310 }}>
              {/* <div className="msg-left">
                <div className="text">
                  <h3>
                    <span>魏</span>
                  </h3>
                  <p>
                    请在30风沙大客户处办卡送电池啥都吃健康的拉扯高你家里到处
                  </p>
                </div>
                <div className="time">23983729813728913</div>
              </div>
              <div className="msg-right">
                <div className="text">
                  <p>
                    请在30风沙大客户处办卡送电池啥都吃健康的拉扯高你家里到处
                  </p>
                  <h3>
                    <span>高</span>
                  </h3>
                </div>
                <div className="time">23983729813728913</div>
              </div>
              <div className="msg-left">
                <h3>
                  <span>魏</span>
                </h3>
                <img
                  src={`${IMAGES_URL}/image/2018/9/19/072073a4037d4eae85bd72cbb60f400d.png?x-oss-process=style/uesstyle`}
                  alt=""
                />
              </div>
              <div className="msg-left">
                <h3>
                  <span>魏</span>
                </h3>
                <img
                  src={`${IMAGES_URL}/image/2018/9/19/239ae7bea97549c49a95981b9cc0140c.jpg?x-oss-process=style/uesstyle`}
                  alt=""
                />
              </div> */}
              {getMessage && (
                <div className="c2c-history-msg">
                  <span onClick={this.getHistoryMsg}>获取历史消息</span>
                </div>
              )}

              {messageList &&
                messageList.map((item, index) => {
                  if (item.msgType === 5) {
                    return (
                      <div key={index} className="msg-public">
                        <div className="time">
                          {stampToDate(item.createTime * 1, "MM-DD hh:mm:ss")}
                        </div>
                        <div className="text">{item.content}</div>
                      </div>
                    );
                  } else {
                    return item.userType === 0 ? (
                      <div key={index} className="msg-left">
                        <div className="time">
                          {stampToDate(item.createTime * 1, "MM-DD hh:mm:ss")}
                        </div>
                        <div className="text">
                          <h3>
                            <span>{askUserName && askUserName.charAt(0)}</span>
                          </h3>
                          {item.msgType === 0 ? (
                            <p>{item.content}</p>
                          ) : (
                            <div>
                              <img
                                onClick={() => {
                                  this.showChatImagePopup(item.content);
                                }}
                                src={item.content}
                                alt=""
                              />
                            </div>
                          )}
                        </div>
                      </div>
                    ) : (
                      <div key={index} className="msg-right">
                        <div className="time">
                          {stampToDate(item.createTime * 1, "MM-DD hh:mm:ss")}
                        </div>
                        <div className="text">
                          {item.msgType === 0 ? (
                            <p>{item.content}</p>
                          ) : (
                            <div>
                              <img
                                onClick={() => {
                                  this.showChatImagePopup(item.content);
                                }}
                                src={item.content}
                                alt=""
                              />
                            </div>
                          )}
                          <h3>
                            <span>{userName && userName.charAt(0)}</span>
                          </h3>
                        </div>
                      </div>
                    );
                  }
                })}
              <div style={{ height: 80 }} />
            </Scrollbars>
            <div className="c2c-msg-input">
              <Input
                placeholder="输入信息, 回车发送"
                value={messageValue}
                onPressEnter={this.sendMessage}
                onChange={this.messageChange}
              />
              {messageValue && (
                <i
                  className="iconfont icon-fasong"
                  onClick={this.sendMessage}
                />
              )}
              {/* {messageValue ? (
                <i
                  className="iconfont icon-fasong"
                  onClick={this.sendMessage}
                />
              ) : (
                <Upload {...props}>
                  <i className="iconfont icon-tupian" />
                </Upload>
              )} */}
            </div>
          </li>
        </ul>
        {popup}
      </Modal>
    );
  }
}

export default PayModal;
